<template>
  <el-main>
    <!-- 搜索栏 -->
    <el-form ref="searchForm" :model="searchForm" :inline="true" size="small">

      <el-form-item>
        <el-select v-model="searchForm.collegeId" style="width:100%" placeholder="请选择学院" @change="searchCollegeChange">
          <el-option
            v-for="item in searchCollegeList"
            :key="item.collegeId"
            :label="item.collegeName"
            :value="item.collegeId"
          />
        </el-select>

      </el-form-item>
      <el-form-item>
        <el-select
          v-model="searchForm.majorId"
          style="width:100%"
          placeholder="请选择专业"
          @change="searchMajorChange"
        >
          <el-option
            v-for="item in searchMajorList"
            :key="item.majorId"
            :label="item.majorName"
            :value="item.majorId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="searchForm.classId"
          style="width:100%"
          placeholder="请选择班级"
          @change="selectClassChange"
        >
          <el-option
            v-for="item in searchClassesList"
            :key="item.classId"
            :label="item.className"
            :value="item.classId"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="stuName">
        <el-input v-model="searchForm.stuName" placeholder="请输入学生名称" />
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 20px; display:flex">
      <el-date-picker
        v-model="searchForm.intoTime"
        size="small"
        type="month"
        value-format="yyyy-MM"
        placeholder="选择入学年份"
      />
      <el-button style="margin-left: 10px;" size="small" icon="el-icon-search" @click="searchBtn">搜索</el-button>
      <el-button size="small" style="color:#FF7670;" icon="el-icon-close" @click="resetBtn">重置</el-button>
      <el-button v-permission="['sys:stuList:add']" size="small" type="primary" icon="el-icon-plus" @click="addBtn">新增</el-button>
      <el-button type="success" size="small" icon="el-icon-bottom" @click="exportTemplate()">下载模版</el-button>
      <el-button style="margin-right: 10px;" type="primary" size="small" icon="el-icon-bottom" @click="exportStu()">导出学生</el-button>
      <el-upload
        class="upload-demo"
        action=""
        :auto-upload="true"
        :multiple="false"
        :show-file-list="false"
        :http-request="uploadFileFn"
        :file-list="fileList"
      >
        <el-button type="warning" size="small" icon="el-icon-top">导入学生</el-button>
      </el-upload>
    </div>
    <sys-dialog
      :title="addDialog.title"
      :height="addDialog.height"
      :width="addDialog.width"
      :visible="addDialog.visible"
      @onClose="onClose"
      @onConfirm="onConfirm"
    >
      <div slot="content">
        <el-form ref="addModel" :model="addModel" :rules="rules" label-width="80px" :inline="false" size="small">
          <el-row>
            <el-col :span="12" :offset="0">
              <el-form-item prop="collegeId" label="所属学院">
                <el-select v-model="addModel.collegeId" style="width:100%" placeholder="请选择学院" @change="selectChange">
                  <el-option
                    v-for="item in collegeList"
                    :key="item.collegeId"
                    :label="item.collegeName"
                    :value="item.collegeId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item prop="majorId" label="所属专业">
                <el-select
                  v-model="addModel.majorId"
                  style="width:100%"
                  placeholder="请选择专业"
                  @change="selectMajorChange"
                >
                  <el-option
                    v-for="item in majorList"
                    :key="item.majorId"
                    :label="item.majorName"
                    :value="item.majorId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" :offset="0">
              <el-form-item prop="classId" label="所属班级">
                <el-select
                  v-model="addModel.classId"
                  style="width:100%"
                  placeholder="请选择班级"
                >
                  <el-option
                    v-for="item in classesList"
                    :key="item.classId"
                    :label="item.className"
                    :value="item.classId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item prop="roleId" label="所属角色">
                <el-select
                  v-model="addModel.roleId"
                  style="width:100%"
                  placeholder="请选择角色"
                >
                  <el-option
                    v-for="item in roleList"
                    :key="item.roleId"
                    :label="item.roleName"
                    :value="item.roleId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" :offset="0">
              <el-form-item prop="stuName" label="学生姓名">
                <el-input v-model="addModel.stuName" />
              </el-form-item></el-col>
            <el-col :span="12" :offset="0">
              <el-form-item prop="sex" label="性别">
                <el-radio-group v-model="addModel.sex">
                  <el-radio :label="'0'">男</el-radio>
                  <el-radio :label="'1'">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" :offset="0">
              <el-form-item prop="phone" label="电话">
                <el-input v-model="addModel.phone" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item prop="intoTime" label="入学时间">
                <el-date-picker
                  v-model="addModel.intoTime"
                  type="month"
                  value-format="yyyy-MM"
                  placeholder="选择日期"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" :offset="0">
              <el-form-item prop="stuNum" label="学号">
                <el-input v-model="addModel.stuNum" />
              </el-form-item>
            </el-col>
            <el-col v-if="addModel.type === '0'" :span="12" :offset="0">
              <el-form-item prop="password" label="密码">
                <el-input v-model="addModel.password" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form></div>
    </sys-dialog>
    <!-- 学生表格列表 -->
    <el-table :data="tableList" :height="tableHeight" border stripe>
      <el-table-column prop="stuName" label="学生名称" />
      <el-table-column prop="stuNum" label="学生学号" />
      <el-table-column prop="collegeName" label="学院" />
      <el-table-column prop="majorName" label="专业" />
      <el-table-column prop="className" label="班级" />
      <el-table-column prop="sex" label="性别">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sex === '0'" type="danger" size="small">男</el-tag>
          <el-tag v-if="scope.row.sex === '1'" type="blue" size="small">女</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="intoTime" label="入学时间" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column v-if="$checkPermission(['sys:stuList:edit', 'sys:stuList:reset', 'ssys:stuList:delete'])" label="操作" align="center" width="320">
        <template slot-scope="scope">
          <el-button v-permission="['sys:stuList:edit']" type="primary" size="small" icon="el-icon-edit" @click="editBtn(scope.row)">修改</el-button>
          <el-button v-permission="['sys:stuList:reset']" type="warning" size="small" icon="el-icon-edit" @click="resetPasswordBtn(scope.row)">重置密码</el-button>
          <el-button v-permission="['sys:stuList:delete']" type="danger" size="small" icon="el-icon-close" @click="deleteBtn(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页插件 -->
    <el-pagination
      :current-page.sync="searchForm.currentPage"
      :page-sizes="[10, 20, 40, 80, 100]"
      :page-size="searchForm.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="searchForm.total"
      background
      @size-change="sizeChange"
      @current-change="currentChange"
    />

  </el-main>

</template>

<script>
import SysDialog from '@/components/dialog/SysDialog.vue'
import { getCollegeApi } from '@/api/major'
import { getListMajorApi } from '@/api/class'
import { addStuApi, deleteStuApi, editStuApi, getClassesApi, getRoleIdApi, getRolesApi, getStuApi, getStuListApi, importStuInfoApi, resetPasswordApi } from '@/api/stu'
export default {
  components: {
    SysDialog
  },
  data() {
    return {
      fileList: [],
      // 角色列表
      roleList: [],
      // 班级列表
      classesList: [],
      searchClassesList: [],
      // 学院列表
      collegeList: [],
      searchCollegeList: [],
      // 专业列表
      majorList: [],
      searchMajorList: [],
      // 学生列表数据
      tableList: [],
      // 表格高度
      tableHeight: 0,
      // 验证规则
      rules: {
        collegeId: [{
          required: true,
          message: '请选择学院'
        }],
        majorId: [{
          required: true,
          message: '请选择专业'
        }],
        classId: [{
          required: true,
          message: '请选择班级'
        }],
        roleId: [{
          required: true,
          message: '请选择角色'
        }],
        stuName: [{
          required: true,
          message: '请输入学生名称',
          trigge: 'blur'
        }],
        sex: [{
          required: true,
          message: '请选择性别'
        }],
        phone: [{
          required: true,
          message: '请输入手机号',
          trigge: 'blur'
        }, {
          pattern: /^1[3-9]\d{9}$/,
          message: '手机号格式不正确',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigge: 'blur'
        }],
        stuNum: [{
          required: true,
          message: '请输入学号',
          trigge: 'blur'
        }],
        intoTime: [{
          required: true,
          message: '请选入学年月'
        }]
      },
      // 搜索参数设置
      searchForm: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        collegeId: '',
        majorName: '',
        collegeName: '',
        className: '',
        classId: '',
        stuName: '',
        intoTime: ''
      },
      // 弹出框设置
      addDialog: {
        title: '',
        height: 300,
        width: 630,
        visible: false
      },
      // 新增表单绑定数据对象
      addModel: {
        stuId: '',
        roleId: '',
        collegeId: '',
        classId: '',
        majorId: '',
        stuName: '',
        sex: '',
        phone: '',
        intoTime: '',
        stuNum: '',
        password: '',
        type: ''
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 260
    })
  },
  created() {
    this.getCollege()
    this.getRoles()
    this.getList()
    this.getSearchCollege()
    this.getSearchMajorList()
    this.getSearchClassesList()
  },
  methods: {
    async uploadFileFn(param) {
      // 如果没有选择班级
      if (!this.searchForm.classId) {
        this.$message.error('请选择班级')
        return false
      }
      // 如果没有选择入学时间
      if (!this.searchForm.intoTime) {
        this.$message.error('请选择入学时间')
        return false
      }
      const file = param.file

      // 通过split方法获取到文件的后缀名
      const fileArr = file.name.split('.')
      const suffix = fileArr[fileArr.length - 1]

      // 只能导入.xls和.xlsx文件
      if (!/(xls|xlsx)/i.test(suffix)) {
        this.$message.warning('文件格式不正确')
        return false
      }

      // 不能导入大小超过2Mb的文件
      if (file.size > 10 * 1024 * 1024) { // 注意单位换算，2MB = 2 * 1024 * 1024 字节
        this.$message('文件过大，请上传小于10MB的文件～')
        return false
      }

      const formData = new FormData()
      formData.append('file', file) // 确保键是字符串，并且和param.file的键一致
      formData.append('classId', this.searchForm.classId)
      formData.append('intoTime', this.searchForm.intoTime)

      console.log(formData)

      // 调用API函数处理文件上传
      const res = await importStuInfoApi(formData) // 假设importStuInfoApi是处理文件上传的API函数
      // console.log(res)

      // 如果API返回成功
      if (res && res.code === 200) {
        this.$message.success(res.msg)
        this.getList()
      }
    },
    async exportTemplate() {
      const abtn = document.createElement('a')
      abtn.href = process.env.VUE_APP_BASE_API_PRO + '/api/student/importStuTemplate'
      abtn.click()
    },
    async exportStu() {
      if (!this.searchForm.classId) {
        this.$message.error('请选择班级')
        return
      }
      const abtn = document.createElement('a')
      abtn.href = process.env.VUE_APP_BASE_API_PRO + '/api/student/exportStuInfo/?classId=' + this.searchForm.classId
      abtn.click()
    },
    async resetPasswordBtn(row) {
      const confirm = await this.$myconfirm('确认重置密码吗？重置后密码为【666666】')
      if (confirm) {
        const params = {
          stuId: row.stuId,
          password: '666666'
        }
        const res = await resetPasswordApi(params)
        if (res && res.code === 200) {
          this.$message.success(res.msg)
        }
      }
    },
    // 解决select清空后不能选择问题
    selectClassChange() {
      this.$forceUpdate()
    },
    searchMajorChange(val) {
      this.getSearchClassesList(val)
    },
    searchCollegeChange(val) {
      this.searchForm.majorId = ''
      this.searchForm.classId = ''
      this.searchMajorList = []
      this.searchClassesList = []
      this.getSearchMajorList(val)
    },
    // 搜索学院列表
    async getSearchCollege() {
      const res = await getCollegeApi()
      if (res && res.code === 200) {
        this.searchCollegeList = res.data
      }
    },
    // 搜索专业列表
    async getSearchMajorList(collegeId) {
      const res = await getListMajorApi({ collegeId: collegeId })
      if (res && res.code === 200) {
        this.searchMajorList = res.data
      }
    },
    // 搜索班级列表
    async getSearchClassesList(majorId) {
      const res = await getClassesApi({ majorId: majorId })
      if (res && res.code === 200) {
        this.searchClassesList = res.data
      }
    },
    // 编辑学生信息
    async editBtn(row) {
      if (this.$refs.addModel !== undefined) {
        this.$refs.addModel.resetFields()
        this.$emptyData(this.addModel)
      }
      // 获取学院列表
      this.getCollege()
      // 根据学生id查询回显数据
      const res = await getStuApi({ stuId: row.stuId })
      if (res && res.code === 200) {
        this.$objCopy(res.data, this.addModel)
        // 获取专业列表
        this.getMajorList(this.addModel.collegeId)
        // 获取班级列表
        this.getClassesList(this.addModel.majorId)
        // 获取角色id
        this.getRoleId(this.addModel.stuId)
      }
      this.addDialog.title = '编辑学生 '
      this.addModel.type = '1'
      this.addDialog.visible = true
    },
    // 删除学生信息
    async deleteBtn(row) {
      const confirm = await this.$myconfirm('确认删除该条数据吗？')
      if (confirm) {
        const res = await deleteStuApi({ stuId: row.stuId })
        if (res && res.code === 200) {
          this.$message.success(res.msg)
          this.getList()
        }
      }
    },
    // 根据学生id查询角色id
    async getRoleId(stuId) {
      const res = await getRoleIdApi({ stuId: stuId })
      if (res && res.code === 200) {
        this.addModel.roleId = res.data.roleId
      }
    },
    // 选择专业发生变化时对应的事件
    selectMajorChange(val) {
      // 清空原来的数据
      this.addModel.classId = ''
      this.getClassesList(val)
    },
    // 选择学院发生变化时对应的事件
    selectChange(val) {
      // 清空原来的数据
      this.addModel.majorId = ''
      this.getMajorList(val)
    },
    // 查询学院列表
    async getCollege() {
      const res = await getCollegeApi()
      if (res && res.code === 200) {
        this.collegeList = res.data
      }
    },
    // 查询专业列表
    async getMajorList(collegeId) {
      const res = await getListMajorApi({ collegeId: collegeId })
      if (res && res.code === 200) {
        this.majorList = res.data
      }
    },
    // 查询班级列表
    async getClassesList(majorId) {
      const res = await getClassesApi({ majorId: majorId })
      if (res && res.code === 200) {
        this.classesList = res.data
      }
    },
    // 查询角色列表
    async getRoles() {
      const res = await getRolesApi()
      if (res && res.code === 200) {
        this.roleList = res.data
      }
    },
    // 查询表格数据
    async getList() {
      const res = await getStuListApi(this.searchForm)
      if (res && res.code === 200) {
        this.tableList = res.data.records
        this.searchForm.total = res.data.total
      }
    },
    // 页容量发生变化
    sizeChange(val) {
      this.searchForm.pageSize = val
      this.getList()
    },
    // 当前页发生变化
    currentChange(val) {
      this.currentChange = val
      this.getList()
    },
    searchBtn() {
      this.getList()
    },
    resetBtn() {
      this.searchForm.collegeName = ''
      this.searchForm.collegeId = ''
      this.searchForm.majorName = ''
      this.searchForm.majorId = ''
      this.searchForm.className = ''
      this.searchForm.classId = ''
      this.searchForm.stuName = ''
      this.searchForm.currentPage = 1
      this.searchForm.pageSize = 10
      this.searchForm.intoTime = ''
      this.getList()
    },
    addBtn() {
      if (this.$refs.addModel !== undefined) {
        this.$refs.addModel.resetFields()
        this.$emptyData(this.addModel)
      }
      this.addDialog.title = '新增学生 '
      this.addModel.type = '0'
      this.addDialog.visible = true
    },
    onClose() {
      this.addDialog.visible = false
    },
    onConfirm() {
      this.$refs.addModel.validate(async(valid) => {
        if (valid) {
          let res = null
          if (this.addModel.type === '0') {
            res = await addStuApi(this.addModel)
          } else {
            res = await editStuApi(this.addModel)
          }
          if (res && res.code === 200) {
            // 消息提示
            this.$message.success(res.msg)
            // 刷新列表
            this.getList()
            // 关闭弹窗
            this.addDialog.visible = false
          }
        }
      })
    }
  }

}
</script>

<style lang="scss" scoped>

</style>
